package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Autowired
    private AdUserMapper addUserMapper;

    //用户登录
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //非空判断
        if (dto == null || dto.getName() == null || dto.getPassword() == null) {
            //参数不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //参数存在,根据用户名查询数据库
        //创建Wrapper
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        //设置查询条件
        wrapper.eq(AdUser::getName, dto.getName());
        //根据用户名查询
        AdUser adUser = addUserMapper.selectOne(wrapper);
        //判断
        if (adUser == null) {
            //不存在该用户,提示错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NameOrPASSWORD_ERROR);
        }
        //存在该用户,获取盐值进行MD5密码加密校验
        String saltPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if (!adUser.getPassword().equals(saltPwd)) {
            //密码校验未通过
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NameOrPASSWORD_ERROR);
        }
        //密码校验通过
        //判断用户状态
        if (adUser.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //修改最近登录时间
        adUser.setLoginTime(new Date());
        //将修改后的用户插入数据库
        addUserMapper.updateById(adUser);
        //生成jwt令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //封装数据
        AdUserVO adUserVO = new AdUserVO();
        try {
            BeanUtils.copyProperties(adUser, adUserVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //创建Map集合,保存数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", adUserVO);
        return ResponseResult.okResult(map);
    }
}
